﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyCommonPortableLib.Common
{
    public static class ExceptionExt
    {
        public static Exception HandleException(this Exception ex)
        {
            if (ex == null)
                return null;

            if (ex.GetType() == typeof(AggregateException))
            {
                var e = ex as AggregateException;
                e.Handle((exception) =>
                {
                    var innerEx = GetInnerException(exception);

                    ex = innerEx;
                    return true;
                });
            }

            return ex;
        }

        private static Exception GetInnerException(Exception ex)
        {
            if (ex.InnerException == null)
                return ex;
            else
                return GetInnerException(ex.InnerException);
        }
    }
}
